package main

import (
	"os"
	"bufio"
	"io"
	"strings"
	"fmt"
	"net/http"
	"strconv"
	"os/exec"
	"bytes"
	"io/ioutil"
)

func main() {

	path:= os.Args[1] //路径
	m3u8Name:= os.Args[2] //m3u8w文件名
	fileName:= os.Args[3] //ts文件名
	FileReadLIne(path,m3u8Name,fileName)

}

func FileReadLIne(path string,m3u8Name string,fileName string) {
	file, err := os.Open(path+m3u8Name)
	if err != nil {
		panic(err)
	}


	reader := bufio.NewReader(file)
	sl := []string{}
	i := 1
	tmepDir:=path+"temp\\"
	ex,err:=PathExists(tmepDir)
	if ex {
		delDir(tmepDir)
	}
	for {
		a, _, c := reader.ReadLine()
		if c == io.EOF {
			break
		}
		if strings.Contains(string(a), "http") {
			err := downFile(string(a), tmepDir, strconv.Itoa(i)+".ts")
			if err != nil {
				panic(err)
			}
			sl = append(sl, tmepDir+strconv.Itoa(i)+".ts")
			i++
		}
	}
	file.Close()
	cmd := "ffmpeg -i concat:"
	for i, v := range sl {
		if i == 0 {
			cmd = cmd + v
		} else {
			cmd = cmd + "|" + v
		}
	}
	cmd = cmd + " -c copy "+path+fileName
	flag:=cmdCommond(cmd)
	if flag{
		delDir(tmepDir)
		err:=os.Remove(path+m3u8Name)
		if err!=nil{
			fmt.Println("remove m3u8 err:",err)
		}
		fmt.Println("合并完成！")
	}

}

func downFile(url string, path string, fileName string) (err error) {
	err2 := os.MkdirAll(path, os.ModePerm)
	if err2 != nil {
		err := fmt.Errorf("make die err:", err2)
		return err
	}
	res, err := http.Get(url)
	if err != nil {
		err = fmt.Errorf("down file err:", err)
		return
	}
	file, err := os.Create(path + fileName)
	if err != nil {
		err = fmt.Errorf("create file err:", err)
		return
	}
	defer file.Close()
	fmt.Println("header",res.Request.URL.Path)
	io.Copy(file, res.Body)
	return nil
}
//文件合并，这里视频文件不适用
func tracefile(str_content []byte, file string) {
	fd, _ := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
	fd.Write(str_content)
	fd.Close()
}

func cmdCommond(ss string) bool  {
	arr := strings.Split(ss, " ")
	ar:=arr[1:]
	cmd := exec.Command(arr[0],ar ...)
	var out bytes.Buffer
	var stderr bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &stderr
	err := cmd.Run()
	if err != nil {
		fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
		fmt.Println(err)
		return false
	}
	fmt.Println("Result: " + out.String())
	return true

}


func delDir(dirPath string){
	files,_:=ioutil.ReadDir(dirPath)
	if len(files)==0{
		err:=os.Remove(dirPath)
		if err!=nil {
			fmt.Errorf("del dir err:",err)
		}
	}else {
		for _,v:=range files{
			err:=os.Remove(dirPath+v.Name())
			if err!=nil {
				fmt.Errorf("del file err:",err)
			}
		}
		delDir(dirPath)
	}
}

// 判断文件夹是否存在
func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
